<template>
	<div class="wrapper">
		<van-nav-bar fixed title="预定订单列表" left-arrow @click-left="$utils.back($route.path);"></van-nav-bar>
		<div class="has-top has-bottom-other">
			<van-tabs @click="tabChange" sticky ref="tabs" :offset-top="$conf.stickyTop" @scroll="scroll">
				<van-tab v-for="(item, index) in statusList" :title="item.value" :name="item.id" :key="index">
					<van-list v-model="loading" :finished="finished" finished-text="没有更多了" :immediate-check="false"
						@load="moreData">
						<div v-for="(item, index) in orderList" :key="index" class="mlr-24 mt-24 fs-24 bg-white br-16 van-clearfix">
							<div class="flex flex-s-c pt-26 pl-24" @click="goDetail(item.OrderId)">
								<div class="flex flex-v-c">
									<!-- <img-box class="is-48" :img-url="goodpic" /> -->
									<span class="fs-34 color-dark ml-8 lh-48">{{ item.StoreName }}</span>
								</div>
								<span class="fs-22 lh-44 bblr-24 btlr-24 status color-white pl-28 pr-18 pos-r">{{ item.StateName }}</span>
							</div>
							<div class="mg-24 pd-24 bg-selfgray flex flex-s-c" @click="goDetail(item.OrderId)">
								<div class="fs-26 color-dark lh-36">
									<p class="mb-16">开始时间：{{ item.BookStartTime }}</p>
									<p>结束时间：{{ item.BookEndTime }}</p>
								</div>
								<div class="fs-26 color-dark">共{{ item.Amount / 2 }}小时</div>
							</div>
							<div class="fs-24 color-gray lh-40 pl-24 pb-24">
								<p v-if="item.CouponMoney !== 0">订单金额:<span class="ml-16 mr-24">{{ item.PriceSum }}元</span> 实付金额:<span
										class="ml-16">{{ item.ReceiptMoney }}元</span></p>
								<p v-else>订单金额:<span class="mlr-16">{{ item.PriceSum }}元</span></p>
								<p>下单时间:<span class="ml-16">{{ item.OrderAddTime }}</span></p>
								<p>预定房间:<span class="ml-16">{{ item.RoomNo }}</span></p>
							</div>
							<div class="flex flex-fe-c pr-24 pb-24">
								<van-button class="ml-15 sef-btn br-32 color-dark fs-24 plr-38 h" native-type="submit"
									v-if="item.State == 3 || item.State == 4 || item.State == 5 || item.State == 6 || item.State == 7"
									@click="againOrder(item, 0)">再次预定</van-button>
								<van-button class="ml-15 br-32 color-white fs-24 plr-38 other-btn" native-type="submit"
									v-if="item.State == 1 && Date.parse(item.BookStartTime) < nowTime && Date.parse(item.BookEndTime) > nowTime"
									@click="OrderBookIn(item)">立即使用</van-button>
								<van-button class="ml-15 sef-btn br-32 color-dark fs-24 plr-38 h" native-type="submit"
									v-if="item.State == 0" @click="CancleOrder(item)">取消订单</van-button>
								<van-button class="ml-15 sef-btn br-32 color-dark fs-24 plr-38 h" native-type="submit"
									v-if="item.State == 1" @click="openRefundApply(item)">申请退款</van-button>
								<van-button class="ml-15 br-32 color-white fs-24 plr-38 other-btn" native-type="submit"
									v-if="item.State == 0" @click="goPay(item)">立即支付</van-button>
								<van-button class="ml-15 br-32 color-white fs-24 plr-38 other-btn" native-type="submit"
									v-if="item.State == 2" @click="GetRoomQrCode(item)">开门码</van-button>
							</div>
						</div>
						<div class="no-data pb-0" v-if="blank">
							<svg-icon icon-class="no-data" />
						</div>
					</van-list>
				</van-tab>
			</van-tabs>
		</div>
		<!-- 开门码弹窗 -->
		<van-dialog v-model="posterShow" class="posterDiv" :showConfirmButton="false" width="80%">
			<div class="poster_main pos-r bg-white bblr-32 bbrr-32 mb-70">
				<SvgIcon icon-class="close" class="fs-60 pos-a closecss z-out color-dark" @goPage="closeQrcode" />
				<div class="qrcode" id="qrcode" ref="qrcode"><img class="is-200" :src="qrcode" /></div>
				<div class="mt-40">将此二维码对准设备，即可开门</div>
			</div>
			<div class="flex flex-sa-c">
				<!--  @click.stop="saveImg" -->
				<div class="flex flex-d-c flex-center flex-1">
					<div class="flex flex-center down br-54">
						<!--  @goPage="saveImg" -->
						<svg-icon icon-class="down" class="fs-40 color-white" />
					</div>
					<!-- fs-28 -->
					<span class="fs-36 lh-40 mt-16 color-white">长按二维码保存图片</span>
				</div>
				<!-- <div class="flex flex-d-c flex-center flex-1">
									<div class="flex flex-center down share br-54">
											<svg-icon icon-class="share" class="fs-32 color-white" />
									</div>
									<span class="fs-28 lh-40 mt-16 color-white">立即分享</span>
							</div> -->
			</div>
		</van-dialog>
		<!-- 退款原因 -->
		<van-dialog v-model="refundApply" title="请输入退款原因" show-cancel-button @confirm="OrderRefundApply"
			@cancel="cancelRefundApply">
			<van-field v-model="param.reason" type="textarea" class="fs-32 mt-15" placeholder="请输入退款原因~" rows="7"
				maxlength="50" />
		</van-dialog>
	</div>
</template>

<script>
import SvgIcon from 'components/SvgIcon'
import imgBox from 'components/imgBox'
import noData from 'components/noData'
import jrQrcode from "jr-qrcode";
import { GetBusinessFunction } from 'api/businessSetting'
import { GetNowTime } from 'api/activity'
import { GetRoomQrCodeByRoomId } from 'api/teaHouse'
import {
	GetOrderBookPage,
	OrderBookIn,
	CancleOrder,
	OrderBookOut,
	GetRoomQrCode,
	OrderRefundApply
} from 'api/teaHouse'
export default {
	components: {
		SvgIcon,
		imgBox,
		noData,
	},
	data() {
		return {
			loading: false, // 加载load
			finished: false, // 无更多数据
			statusList: [{
				value: '全部',
				id: -1
			},
			{
				value: '待付款',
				id: 0
			},
			{
				value: '已预定',
				id: 1
			},
			{
				value: '已使用',
				id: 2
			},
			{
				value: '已完成',
				id: 5
			},
			{
				value: '已取消',
				id: 6
			},
			], // 订单列表状态
			requestData: {
				state: -1,
				PageIndex: 1,
				PageSize: 10,
				saleType: 1,
			}, // 订单列表查询
			orderList: [], // 订单列表数据
			blank: false, // 是否为空数据
			posterShow: false, // 二维码弹窗显示
			qrcode: '', // 二维码图片地址
			ewm: '', // 点击开门码时存储所带数据生成二维码内容
			infos: {}, // 点击下载二维码存储所带数据(h5下载二维码图片名称)嵌套小程序只需长按图片保存所以
			refundApply: false, // 退款原因弹窗
			param: { // 退款参数
				OrderId: '', // 退款订单id
				reason: '', // 退款原因
			},
			switch30: 0, //申请退款是否显示(0不显示 1显示)
			nowTime: '',
		}
	},
	created() {
		this.GetBusinessFunction()
		this.setInterval()
	},
	mounted() {
	},
	activated() {
		// 获取列表
		this.reset()
	},
	methods: {
		//获取开关权限
		GetBusinessFunction() {
			GetBusinessFunction(30).then(res => {
				if (res) {
					this.switch30 = res.Data[0].Value;
				}
			})
		},
		goDetail(id) {
			this.$router.push({
				path: 'teaOrderDetail',
				query: {
					id: id,
					saleType: 1,
				}
			})
		},
		// 获取列表
		GetOrderBookPage() {
			const _this = this
			_this.loading = true
			GetOrderBookPage(_this.requestData).then(res => {
				if (res.State == 0) {
					return
				}
				if (_this.requestData.PageIndex >= res.Data.TotalAmout) {
					_this.finished = true
				} else {
					_this.finished = false
				}
				_this.blank = false
				_this.loading = false
				_this.orderList = _this.orderList.concat(res.Data.Data)
				if (_this.orderList.length == 0) {
					_this.blank = true
				}
				_this.orderList.map(function (item, index) {
					if (new Date(item.BookEndTime.split(' ')[0]).getTime() < new Date(_this.$utils.dateFomat('yyyy-mm-dd HH:MM:SS', new Date()).split(' ')[0]).getTime() && item.State == 2) {
						item.noOver = true
					}
				})
				console.log(_this.orderList, 'this._this.orderList');
			})
		},
		// 上拉加载更多
		moreData() {
			this.requestData.PageIndex = this.requestData.PageIndex + 1
			this.GetOrderBookPage()
		},
		// 重新请求
		reset() {
			this.requestData.PageIndex = 1
			this.requestData.PageSize = 10
			this.requestData.saleType = 1
			this.orderList = []
			// 获取列表
			this.GetOrderBookPage()
		},
		// tab置顶
		scroll(data) {
			if (data.isFixed) {
				this.$refs.tabs.$refs.nav.classList.add('van-tabs__nav_Fixed')
			} else {
				this.$refs.tabs.$refs.nav.classList.remove('van-tabs__nav_Fixed')
			}
		},
		// tab切换
		tabChange(e) {
			// 状态id
			this.requestData.states = e
			if (e === 6) {
				this.requestData.states = '3,6,7'
			}
			// 获取列表
			this.reset()
		},
		// 立即支付
		goPay(item) {
			window.location.href = this.$LocalDomain + '/m/product/PayOrder?id= ' + item.OrderId + '&&singleflag=1&&isBookOrder=2'
		},
		// 入住
		OrderBookIn(item) {
			OrderBookIn(item.OrderId).then(res => {
				if (res.Data) {
					// 获取列表
					this.reset()
				}
			})
		},
		// 退房
		OrderBookOut(item) {
			OrderBookOut(item.OrderId).then(res => {
				if (res.Data) {
					// 获取列表
					this.reset()
				}
			})
		},
		// 申请退款
		openRefundApply(item) {
			this.refundApply = true
			this.param.OrderId = item.OrderId
		},
		// 确认申请退款
		OrderRefundApply() {
			if (this.param.reason == '') {
				this.$toast('请输入退款原因')
				return
			}
			OrderRefundApply({
				orderId: this.param.OrderId,
				reason: this.param.reason,
				image: ''
			}).then(res => {
				if (res.Data) {
					// 获取列表
					this.reset()
				}
			})
		},
		// 取消申请退款
		cancelRefundApply() {
			this.param.reason = ''
			this.refundApply = false
		},
		// 取消订单
		CancleOrder(item) {
			CancleOrder(item.OrderId).then(res => {
				if (res.Data) {
					// 获取列表
					this.reset()
				}
			})
		},
		// 再次预定
		againOrder(item, type) {
			this.$router.push({
				path: '/teaOrderSubmit',
				query: {
					storeId: item.StoreId,
					productId: item.ProductId,
					orderId: item.OrderId,
					type: type,
					bookStoreId: item.BookStoreId
				}
			})
		},
		// 续单
		renewalOrder(item, type) {
			console.log(item, 'item.orderId');
			this.$router.push({
				path: '/orderSubmit',
				query: {
					storeId: item.StoreId,
					productId: item.ProductId,
					orderId: item.OrderId,
					type: type,
					bookStoreId: item.BookStoreId
				}
			})
		},
		// 开门码
		GetRoomQrCode(item) {
			this.infos = item
			GetRoomQrCode(item.OrderId).then(res => {
				if (res.State == 0) {
					return
				}
				this.ewm = res.Data
				this.$nextTick(() => {
					let imgBase64 = jrQrcode.getQrBase64(this.ewm, {//生成二维码
						padding: 10,   // 二维码四边空白（默认为10px）
						width: 200,  // 二维码图片宽度（默认为256px）
						height: 200,  // 二维码图片高度（默认为256px）
						correctLevel: QRErrorCorrectLevel.H,    // 二维码容错level（默认为高）
						reverse: false,        // 反色二维码，二维码颜色为上层容器的背景颜色
						background: "#ffffff",    // 二维码背景颜色（默认白色）
						foreground: "#000000"     // 二维码颜色（默认黑色）
					});  //options为配置对象，支持以下配置参数：
					this.qrcode = imgBase64
				})
				this.posterShow = true
			})
		},
		GetRoomQrCodeByRoomId(item) {
			this.infos = item
			GetRoomQrCodeByRoomId({ RoomId: item.RoomId, IsOpenOutDoor: item.IsOpenOutDoor }).then(res => {
				if (res.State == 0) {
					return
				}
				this.ewm = res.Data
				this.$nextTick(() => {
					let imgBase64 = jrQrcode.getQrBase64(this.ewm, {//生成二维码
						padding: 10,   // 二维码四边空白（默认为10px）
						width: 200,  // 二维码图片宽度（默认为256px）
						height: 200,  // 二维码图片高度（默认为256px）
						correctLevel: QRErrorCorrectLevel.H,    // 二维码容错level（默认为高）
						reverse: false,        // 反色二维码，二维码颜色为上层容器的背景颜色
						background: "#ffffff",    // 二维码背景颜色（默认白色）
						foreground: "#000000"     // 二维码颜色（默认黑色）
					});  //options为配置对象，支持以下配置参数：
					this.qrcode = imgBase64
				})
				this.posterShow = true
			})
		},
		// 为了防止重复生成二维码，使用置空
		closeQrcode() {
			this.posterShow = false
			setTimeout(function () {
				this.qrcode = ''
			}, 150)
		},
		// 下载二维码
		saveImg() {
			let myCanvas = document.getElementById("qrcode").getElementsByTagName("img")
			let elink = document.createElement("a")
			elink.style.display = "none"
			document.body.appendChild(elink)
			elink.href = myCanvas[0].src
			elink.download = this.infos.RoomNo + this.infos.RoomName + "开门码"
			elink.click()
			document.body.removeChild(elink)
		},
		setInterval() {
			var that = this;
			//当前时间
			GetNowTime().then(rsp => {
				if (rsp.State == 1) {
					that.nowTime = new Date(rsp.Data.replace(/-/g, '/')).getTime();
					that.interval = setInterval(e => {
						that.nowTime += 1000;
					}, 1000)
				}
			})
		},
	}
}
</script>

<style lang="scss" scoped>
.status {
	margin-right: -12px;
	background-color: #FDB52A;
}

.sef-btn {
	height: 64px;
	line-height: 64px;
	border: 1px solid #666666 !important;
}

.other-btn {
	@include bg-primary;
	height: 64px;
	line-height: 64px;
	border: 1px solid transparent !important;
}

.closecss {
	top: 20px;
	right: 16px;
	width: 50px;
	height: 50px;
}

.poster_main {
	text-align: center;
	padding: 62px 60px 62px;

	img {
		width: 450px;
		height: 450px;
	}

	p {
		font-size: 28px;
		color: #F54F1B;
		padding: 30px 0;
		font-weight: 500;
	}

	div {
		font-size: 28px;
		color: #333;
		font-weight: 400;
	}
}

/deep/.posterDiv {
	background-color: transparent;
}

.down {
	width: 96px;
	// height: 96px;
	// background: #8AC24C;
}

.share {
	background-color: #FDB52A;
}

.status:after {
	position: absolute;
	bottom: -10px;
	right: 0;
	width: 0;
	height: 0;
	border-right: 12px solid transparent;
	border-top: 10px solid #FDB52A;
	content: "";
}

/deep/.van-list__finished-text {
	color: #333;
}

/deep/.qrcode canvas {
	padding: 20px;
}

/deep/.van-field__control {
	padding: 8px;
	background-color: #F7F7F7;
}
</style>
